package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Activity;
import com.qk.entity.Clue;
import com.qk.management.mapper.ActivityMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.ActivityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@SuppressWarnings("all")
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ClueMapper clueMapper;

    @Override
    public PageResult<Activity> page(Integer channel, Integer type, Integer status, Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<Activity> activity=activityMapper.page(channel, type, status);
        Page<Activity> rows = (Page<Activity>)activity;

        return PageResult.<Activity>builder().total(rows.getTotal()).rows(rows.getResult()).build();
    }

    @Override
    public void addActivity(Activity activity) {
        boolean hasNull = BeanUtil.hasNullField(activity, "id","discount","voucher","updateTime", "createTime");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        activity.setCreateTime(LocalDateTime.now());
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.addActivity(activity);
    }

    @Override
    public Activity selectId(Integer id) {
        Activity activity=activityMapper.selectId(id);
        return activity;
    }

    @Override
    public void updateActivity(Activity activity) {
        activity.setUpdateTime(LocalDateTime.now());
        activityMapper.updateActivity(activity);
    }

    @Override
    public void deleteActivity(Integer id) {
        List<Clue> clues=clueMapper.selectList(Wrappers.lambdaQuery(Clue.class).eq(Clue::getActivityId,id));
        if(!clues.isEmpty()){
            log.error("当前活动{}被线索 引用，无法删除", id);
            CommonException.throwCommonException(ParamEnum.ACTIVITY_REFERENCE_ERROR);
        }

        activityMapper.deleteActivity(id);
    }

    @Override
    public List<Activity> selectType(Integer type) {
        List<Activity> activity=activityMapper.selectType(type);
        return activity;
    }


}
